import org.springframework.web.multipart.MultipartHttpServletRequest
import org.springframework.web.multipart.commons.CommonsMultipartFile
import org.springframework.util.FileCopyUtils

class BabyController {

  def index = { redirect(action: list, params: params) }

  // the delete, save and update actions only accept POST requests
  static allowedMethods = [delete: 'POST', save: 'POST', update: 'POST']

  def list = {
    params.max = Math.min(params.max ? params.max.toInteger() : 10, 100)
    [babyInstanceList: Baby.list(params), babyInstanceTotal: Baby.count()]
  }

  def show = {
    def babyInstance = Baby.get(params.id)

    if (!babyInstance) {
      flash.message = "Baby not found with id ${params.id}"
      redirect(action: list)
    }
    else { return [babyInstance: babyInstance] }
  }

  def delete = {
    def babyInstance = Baby.get(params.id)
    if (babyInstance) {
      try {
        babyInstance.delete()
        flash.message = "Baby ${params.id} deleted"
        redirect(action: list)
      }
      catch (org.springframework.dao.DataIntegrityViolationException e) {
        flash.message = "Baby ${params.id} could not be deleted"
        redirect(action: show, id: params.id)
      }
    }
    else {
      flash.message = "Baby not found with id ${params.id}"
      redirect(action: list)
    }
  }

  def edit = {
    def babyInstance = Baby.get(params.id)

    if (!babyInstance) {
      flash.message = "Baby not found with id ${params.id}"
      redirect(action: list)
    }
    else {
      return [babyInstance: babyInstance]
    }
  }

  def update = {
    def babyInstance = Baby.get(params.id)
    if (babyInstance) {
      if (params.version) {
        def version = params.version.toLong()
        if (babyInstance.version > version) {

          babyInstance.errors.rejectValue("version", "baby.optimistic.locking.failure", "Another user has updated this Baby while you were editing.")
          render(view: 'edit', model: [babyInstance: babyInstance])
          return
        }
      }
      babyInstance.properties = params
      if (!babyInstance.hasErrors() && babyInstance.save()) {
        flash.message = "Baby ${params.id} updated"
        redirect(action: show, id: babyInstance.id)
      }
      else {
        render(view: 'edit', model: [babyInstance: babyInstance])
      }
    }
    else {
      flash.message = "Baby not found with id ${params.id}"
      redirect(action: edit, id: params.id)
    }
  }

  def create = {
    def babyInstance = new Baby()
    babyInstance.properties = params
    return ['babyInstance': babyInstance]
  }

  def save = {
    def babyInstance = new Baby(params)
    if (!babyInstance.hasErrors() && babyInstance.save()) {
      flash.message = "Baby ${babyInstance.id} created"
      redirect(action: show, id: babyInstance.id)
    }
    else {
      render(view: 'create', model: [babyInstance: babyInstance])
    }
  }

  def updateBasic = {
    println params
    def babyInstance = Baby.get(params.id)
    if (babyInstance) {
      if (params.version) {
        def version = params.version.toLong()
        if (babyInstance.version > version) {

          babyInstance.errors.rejectValue("version", "baby.optimistic.locking.failure", "Another user has updated this Baby while you were editing.")
          render(view: 'edit', model: [babyInstance: babyInstance])
          return
        }
      }
      babyInstance.properties = params
      if (!babyInstance.hasErrors() && babyInstance.save()) {
        flash.message = "Baby ${params.id} updated"
        redirect(controller: 'b', action: edit, id: babyInstance.id)
      }
      else {
        render(view: 'edit', model: [babyInstance: babyInstance])
      }
    }
    else {
      flash.message = "Baby not found with id ${params.id}"
      redirect(controller: 'b', action: edit, id: params.id)
    }
  }

  def updateHeadImg = {
    def baby = Baby.get(params.id)
    MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request
    CommonsMultipartFile file = (CommonsMultipartFile) multiRequest.getFile("img")
    if (file == null || file == "") {
      flash.message = "Please chose a file to upload before submiting"
      redirect(controller: 'b', action: edit, id: params.id)
    } else if(baby) {
      def pathname = grailsApplication.config.uploadPath
      def urlPrefix = grailsApplication.config.uploadUrlPrefix
      def curDir = new File(pathname)
      if (!curDir.exists()) curDir.mkdirs()
      String sep = System.getProperty("file.separator");
      def originalFileName = file.getOriginalFilename()
      def uploadFileName = curDir.getAbsolutePath() + sep + file.getOriginalFilename()
      def outputDirectory = curDir.getAbsolutePath()
      File uploadedFile = new File(uploadFileName);
      FileCopyUtils.copy(file.bytes, uploadedFile);
      def imageTool = new ImageTool()
      imageTool.load(uploadFileName)
      def fname = uploadFileName.substring(0, uploadFileName.indexOf('.'))
      def fnameext = uploadFileName.substring(uploadFileName.indexOf('.') + 1)
      [50,200].each {
          def tempName = fname + "_" + it + "." + fnameext
          imageTool.load(uploadFileName)
          imageTool.thumbnailSpecial(it, 500, 1, 2)
          imageTool.writeResult(tempName, "JPEG")
          //imageTool.restoreOriginal()
      }
      baby.headImg = urlPrefix + originalFileName
      baby.save()
      flash.message = "${baby.nickName} updated head image."
      redirect(controller: 'b', action: edit, id: params.id)
    }
  }
}
